package io.mvvm.nio.channel;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @program: Netty
 * @description: FileChannel 写入
 * @author: 潘
 * @create: 2021-01-17 20:51
 **/
public class FileChannelWriteExample {
    public static void main(String[] args) throws Exception {
        String name = "zhangsan";
        // 创建一个输出流
        FileOutputStream stream = new FileOutputStream("E:\\fileName.txt");
        // 通过 stream 获取 FileChannel
        FileChannel channel = stream.getChannel();
        // 创建一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 将 name 放入到 buffer中
        buffer.put(name.getBytes(StandardCharsets.UTF_8));
        // 对 buffer 进行 flip，即读写转换
        buffer.flip();
        // 将 buffer 写入到 channel 中
        channel.write(buffer);
        channel.close();
    }
}
